'''
Created on 13/07/2010

@author: eh01
'''
import unittest
from services.http_service import Handler
from BaseHTTPServer import HTTPServer
import StringIO
from datastore.resource import Resource, ResourceDict
from datastore.spaces import Spaces
from datastore.uri import Uri
import os


class HandlerTest(unittest.TestCase):

    HTTP_SERVICE_FILE_PATH = '../../src/services/http_service.xml'
    HTTP_SERVICE_FILE_PATH_WITH_ANT_TASK = '../src/services/http_service.xml'
    
    def setUp(self):
        pass


    def tearDown(self):
        pass

    def get_http_service_res(self):
        http_service_rs = Resource(type="temp")
        if os.path.isfile(HandlerTest.HTTP_SERVICE_FILE_PATH):
            http_service_rs.load_from_file(HandlerTest.HTTP_SERVICE_FILE_PATH)
        else:
            http_service_rs.load_from_file(HandlerTest.HTTP_SERVICE_FILE_PATH_WITH_ANT_TASK)
        return http_service_rs
    
    def test_check_url_valid_for_site(self):
        valid_paths_patterns = ['^/$',
                              '^/admin/restart$',
                              '^/login/?$',
                              '^/login/.*$'
                              ]
        site_res = Resource(type="term:base/services/http/site")
        site_res.valid_paths_patterns = valid_paths_patterns
        test_url_patterns = [('/', True),
                             ('/admin/restart', True),
                             ('/login', True),
                             ('/login/', True),
                             ('/login/retry', True),
                             ('/secure', False),
                             ('/loginsecure', False)]
        client_address = ('localhost', 6101)
        server = HTTPServer(client_address, Handler)
        handler = Handler(RequestStub(), client_address, server)
        for url_pattern, result in test_url_patterns:            
            self.assertEqual(result, handler.check_path_valid_for_site(url_pattern, site_res))

    def test_find_mapping(self):
        req_uri_1 = Uri('a/b/c')
        req_uri_2 = Uri('d/e/f')
        http_service_rs = self.get_http_service_res()
        service_def_rs = http_service_rs.services['base/services/http_service']
        spaces = Spaces()
        client_address = ('localhost', 6101)
        server = HTTPServer(client_address, Handler)
        handler = Handler(RequestStub(), client_address, server)

        # test no mapping
        mapping = handler.find_mapping(spaces, service_def_rs, req_uri_1, 'POST')
        self.assertEqual(None, mapping)

        # test mapping with no corresponding http method
        mapping_uri = Uri('x/y/z')
        expected_mapping = None
        http_service_rs = self.get_http_service_res()
        mappings_res = Resource(type="term:base/services/http/url_mapping")
        mappings_res.map = {req_uri_2:ResourceDict({'http_methods': ['GET']})}
        mappings_res.uri = mapping_uri           
        spaces.put(service_def_rs.options.mapping_prefix + req_uri_2, mappings_res)     
        spaces.put(service_def_rs.options.mapping_prefix + req_uri_2, mappings_res)
        mapping = handler.find_mapping(spaces, service_def_rs, req_uri_2, 'POST')
        self.assertEqual(expected_mapping, mapping)   
        
        # test mapping with corresponding http method
        expected_mapping = ResourceDict({'http_methods': ['GET', 'POST']})
        mappings_res.map = {req_uri_2:expected_mapping}
        spaces.put(service_def_rs.options.mapping_prefix + req_uri_2, mappings_res)
        mapping = handler.find_mapping(spaces, service_def_rs, req_uri_2, 'POST')
        self.assertEqual(expected_mapping, mapping)        
        
    
class RequestStub(object):
    """
    Class to stub out the Request Object for testing of the BaseHTTPRequestHandler.
    """    
    def makefile(self, arg1, arg2):
        return StringIO.StringIO()
    
if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()